<?php
namespace app\admin\model;

class Config extends AdminModel
{
	protected $name = 'system_config';
	
	/**
	 * 新增、更新需要操作的字段
	 */
	protected $submitField = [

	];

	protected $append = [
		'type_text',
	];

	public function getTypeTextAttr($value,$data){
		$html = \think\facade\Config::get('html');
		return $html[$data['type']];
	}

	public static function onAfterInsert( Config $config ): void
	{
		self::getConfigCache(true);
	}

	public static function onAfterDelete(  Config $config): void
	{
		self::getConfigCache(true);
	}

	public static function onAfterUpdate( Config $config): void
	{
		self::getConfigCache(true);
	}

	public static function getConfigCache($refresh=false){
		if(cache('?config') && !$refresh){
			return cache('config');
		}

		$config = $nConfig = [];

		$config = self::order('sort asc')->select();

		if($config->isEmpty()){
			return [];
		}

		$config = $config->toArray();

		/**
		 * nConfig长这样 ['group' => [ 'key' => 'value']]
		 */
		foreach($config as $key => $value){
			if(in_array($value['type'],['files','images','image','file'])){
				if(strpos($value['value'],',')!== false){
					$value['value'] = FileManager::where('id','in',$value['value'])->column('path');
				}else{
					$value['value'] = FileManager::where('id','in',$value['value'])->value('path');
				}
			}elseif(in_array($value['type'],['checkbox'])){
				$value['value'] = explode(',',$value['value']);
			}
			$nConfig[$value['group']][$value['key']] = $value['value'];
			unset($config[$key]);
		}

		if(!env('APP_DEBUG')){
			cache('config',$nConfig);
		}

		return $nConfig;
	}
}

